﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;

namespace MyMesComp
{
    internal static class PostHelper
    {
        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <param name="dic"></param>
        /// <param name="mode">发送的方式</param>
        /// <returns></returns>
        public static string Post(string url, Dictionary<string, string> dic, SendPostMode mode = SendPostMode.x_www_form_urlencoded)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = mode.GetEnumDescription();

            #region 添加Post 参数

            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }

            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }

            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }

            return result;
        }

        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <param name="content">Post提交数据内容(utf-8编码的)</param>
        /// <param name="mode">发送的方式</param>
        /// <returns></returns>
        public static string Post(string url, string content, SendPostMode mode = SendPostMode.x_www_form_urlencoded)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = mode.GetEnumDescription();

            #region 添加Post 参数
            byte[] data = Encoding.UTF8.GetBytes(content);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
        /// <summary>
        /// Post方式获取指定类型的返回值
        /// </summary>
        /// <typeparam name="T">返回值的类型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="content">请求的内容，一般为json串</param>
        /// <param name="mode">请求模式，json或者x_www_form_urlencoded</param>
        /// <returns></returns>
        public static T Post<T>(string url, string content, SendPostMode mode = SendPostMode.x_www_form_urlencoded) where T : class
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = mode.GetEnumDescription();

            #region 添加Post 参数
            byte[] data = Encoding.UTF8.GetBytes(content);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result.Deserialize<T>();
        }
        /// <summary>
        /// 同步发送
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public static string SendHttpPost(string apiUrl, String jsonData)
        {
            try
            {

                if (string.IsNullOrEmpty(apiUrl)) throw new Exception("接口地址不能为空");
                if (string.IsNullOrEmpty(jsonData)) throw new Exception("JSON数据不能为空");

                using (var client = new HttpClient())
                {
                    var content = new FormUrlEncodedContent(new[]
                    {
                    new KeyValuePair<string, string>("jsonData", jsonData.Replace("\r\n", ""))
                });

                    // 同步发送请求
                    var response = client.PostAsync(apiUrl, content).Result;
                    response.EnsureSuccessStatusCode();
                    string responseString = response.Content.ReadAsStringAsync().Result;

                    var result = JObject.Parse(responseString);
                    return result.ToString(Newtonsoft.Json.Formatting.Indented);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"请求过程中出现错误: {ex.Message}", ex);
            }
        }
    }

    internal enum SendPostMode
    {
        [Description("application/json")]
        Json = 1,
        [Description("application/x-www-form-urlencoded")]
        x_www_form_urlencoded = 2,
    }
}
